package com.jqb.sturts2lab02.action;

import java.io.File;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class Struts2FileUploadAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	private String describe;
	/**
	 * 按Struts2的约束提供变量获取文件字段,文件名,文件类型
	 */
	private List<File> userfile;
	private List<String> userfileFileName;
	private List<String> userfileContentType;

	public String getDescribe() {
		return describe;
	}

	public void setDescribe(String describe) {
		this.describe = describe;
	}

	public List<File> getUserfile() {
		return userfile;
	}

	public void setUserfile(List<File> userfile) {
		this.userfile = userfile;
	}

	public List<String> getUserfileFileName() {
		return userfileFileName;
	}

	public void setUserfileFileName(List<String> userfileFileName) {
		this.userfileFileName = userfileFileName;
	}

	public List<String> getUserfileContentType() {
		return userfileContentType;
	}

	public void setUserfileContentType(List<String> userfileContentType) {
		this.userfileContentType = userfileContentType;
	}

	@Override
	public String execute() throws Exception {
		/**
		 * 设置上传文件路径
		 */
		String uploaddir = ServletActionContext.getServletContext().getRealPath("userupload");

		/**
		 * 便利方法
		 */
		if (userfile != null) {
			for (int i = 0; i < userfile.size(); i++) {
				if (userfile.get(i) != null) {
					FileUtils.copyFile(userfile.get(i), new File(uploaddir,	userfileFileName.get(i)));
				}
			}
		}
		
		/**
		 * 传统方法
		 */
		/*
		if (userfile != null) {
			for (int i = 0; i < userfile.size(); i++) {
				if (userfile.get(i) != null) {
					InputStream is = new FileInputStream(userfile.get(i));
					OutputStream os = new FileOutputStream(new File(uploaddir, userfileFileName.get(i)));
					byte[] buffer = new byte[512];
					int length = 0;
					while (-1 != (length = is.read(buffer))) {
						os.write(buffer, 0, length);
					}
					os.close();
					is.close();
				}
			}
		}
		*/
		return SUCCESS;
	}
	
}
